package main

import (
	"fmt"
	"zinx/ziface"
	"zinx/znet"
)

type PingRouter struct {
	znet.BaseRouter
}

func (pr *PingRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call PingRouter Handle...")
	//先读取客户端数据，再回写ping
	fmt.Println("recv from client: msgId = ", request.GetMsgId(),
		", data = ", string(request.GetData()))
	err := request.GetConnection().SendMsg(200, []byte("ping...ping...ping"))
	if err != nil {
		fmt.Println("call back ping...ping...ping...err")
	}
}

type PongRouter struct {
	znet.BaseRouter
}

func (pr *PongRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call PongRouter Handle...")
	//先读取客户端数据，再回写ping
	fmt.Println("recv from client: msgId = ", request.GetMsgId(),
		", data = ", string(request.GetData()))
	err := request.GetConnection().SendMsg(201, []byte("pong...pong...pong"))
	if err != nil {
		fmt.Println("call back pong...pong...pong...err")
	}
}

// DoConnectionBegin 创建连接之后的Hook函数
func DoConnectionBegin(conn ziface.IConnection) {
	fmt.Println("=======>DoConnectionBegin is Called...")
	err := conn.SendMsg(202, []byte("Hello"))
	if err != nil {
		fmt.Println(err)
	}
	//设置连接属性
	fmt.Println("Set conn property...")
	conn.SetProperty("Name", "mwh")
	conn.SetProperty("GitHub", "github")
	conn.SetProperty("Home", "home")
}

// DoConnectionLost 销毁连接之前的Hook函数
func DoConnectionLost(conn ziface.IConnection) {
	fmt.Println("=======>DoConnectionLost is Called...")
	fmt.Println("conn Id = ", conn.GetConnID(), " is lost...")
	//获取连接属性
	if name, err := conn.GetProperty("Name"); err == nil {
		fmt.Println("Name = ", name)
	}
	if github, err := conn.GetProperty("GitHub"); err == nil {
		fmt.Println("Github = ", github)
	}
	if home, err := conn.GetProperty("Home"); err == nil {
		fmt.Println("Home = ", home)
	}
}

func main() {
	//1.创建一个server句柄
	s := znet.NewServer("[zinx V0.9]")
	//2.注册Hook函数
	s.SetOnConnCreate(DoConnectionBegin)
	s.SetOnConnDestroy(DoConnectionLost)
	//3.给当前zinx框架添加一个自定义的router
	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &PongRouter{})
	//4.启动server
	s.Start()
}
